#!/usr/bin/env bash

_mv_info_tips_() 
{
    echo "$1 is_from_dir $cur_dir" >> $2
}

_get_safe_check_num_()
{
    cur_dir=`pwd`
    local cannot_rm_dirs=("$HOME" "/" /usr /usr/lib /usr/local /root /Users /home)
    local count=0
    for arg in "$@"
    do
        local father_path
        local absolute_path_arg
        local _cur_dir_=`pwd`

        if [ "${arg:0:1}" == "/" ] ; then
            absolute_path_arg="$arg"
        else
            absolute_path_arg="$cur_dir/$arg"
        fi

        if [ -d "$absolute_path_arg" ] ; then
            path=`cd "$absolute_path_arg" && pwd`
            father_path=`dirname "$path"`
            cd "$_cur_dir_"
        elif [ -f "$absolute_path_arg" ] ; then
            path=`dirname "$absolute_path_arg"`
            father_path=`cd "$path" && pwd`
            cd "$_cur_dir_"
        fi

        for _dir in ${cannot_rm_dirs[@]}
        do
            if [ -d "$absolute_path_arg" ] ; then
                if [ "$absolute_path_arg" == $_dir ] ; then
                    let count=100
                    return $count
                fi
            fi

            if [ "$_dir" == "$father_path" ] ; then
                let ++count
                if [ $count -ge 4 ] ; then
                    return $count
                fi
            fi
        done
    done
    return $count
}

mv_to_trash()
{
    local cur_dir=`pwd`

    _get_safe_check_num_ "$@"
    local check_num=$?
    if [ $check_num -ge 3 ] ; then
        echo "error, return check_num:$check_num you maybe want to rm system direcoty, this rm is must be forbidden !!!"
        return 1
    fi

    #local uuid_str=$(mktemp -u)
    ##uuid_str=${uuid_str:0:4}
    #uuid_str=${uuid_str##*.}
    #uuid_str=${uuid_str:0:4}

    local uuid_str=$[$RANDOM%9000+1000]
    local trash_dir=$HOME/.Trash/`date +%Y_%m_%d__%H_%M_%S`_${uuid_str}
    local path_info=$trash_dir/path_info.txt
    if [ ! -d $trash_dir ];then
        mkdir -p $trash_dir
        touch $path_info
    fi

    for arg in "$@"
    do
        #echo "arg is:$arg"
        if [[ "$arg" == -* ]];then
            continue
        fi

        if [  -d "$arg" ];then
            if [[ "$1" == -r* ]];then
                mv "$arg" $trash_dir
                _mv_info_tips_ "$arg" "$path_info"
            else
                echo "\"$arg\" is directory, use rm -r"
            fi
        elif [ -f "$arg" ];then
            mv "$arg" $trash_dir
            _mv_info_tips_ "$arg" "$path_info"
        else
            echo "\"$arg\" does not exist."
        fi
    done
}
